import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Staff, Identity } from 'src/schemas/staff/staff.interface';
import { CredentialsDto } from 'src/dto/credentials.dto';
import { PasswordService } from 'src/common/password/password.service';
import { StaffsPaginationDto } from 'src/dto/staffs-pagination.dto';

@Injectable()
export class StaffsService {
  constructor(
    @InjectModel('Staff') private readonly staffModel: Model<Staff>,
    private readonly passwordService: PasswordService,
  ) {}

  /**
   * 通过账号查找员工
   * @param account 账号
   */
  findStaffByAccount(account: string) {
    return this.staffModel.findOne({ account });
  }

  /**
   * 创建一个身份员工
   * @param credentialsDto 用户凭据
   * @param identity 身份
   */
  async createIdentityStaff(
    credentialsDto: CredentialsDto,
    identity: Identity,
  ) {
    // 哈希一下密码
    const password = await this.passwordService.hash(credentialsDto.password);
    // 在数据库中创建用户
    const createdUser = new this.staffModel({
      account: credentialsDto.account,
      password,
      identity: identity,
    } as Staff);
    // 返回用户
    return await createdUser.save();
  }

  /**
   * 通过 _id 删除员工
   * @param _id 员工 _id
   */
  deleteById(_id: string) {
    return this.staffModel.deleteOne({ _id });
  }

  /**
   * 通过 _id 更新员工密码
   * @param _id 员工 _id
   */
  async updatePasswordById(_id: string, newPassword: string) {
    // 哈希一下密码
    const password = await this.passwordService.hash(newPassword);

    return await this.staffModel.updateOne({ _id }, {
      password,
    } as Staff);
  }

  /**
   * 查询一些员工
   * @param staffsPaginationDto 查询条件
   */
  find(staffsPaginationDto: StaffsPaginationDto) {
    const { pageIndex, pageSize } = staffsPaginationDto;
    return this.staffModel
      .find({ identity: Identity.Staff }, '_id account')
      .skip((pageIndex - 1) * pageSize)
      .limit(pageSize);
  }

  /**
   * 获得员工的总数
   */
  count() {
    return this.staffModel.find({ identity: Identity.Staff }).countDocuments();
  }
}
